import { Space } from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons';
import React from 'react';
import { useModel, history } from 'umi';
import Avatar from './AvatarDropdown';
import HeaderSearch from '../HeaderSearch';
import styles from './index.less';
import routes from '../../../config/routes';

export type SiderTheme = 'light' | 'dark';

const flatTree = (data: any, treeMap = [], initialState: any) => {
  if (data && data.length === 0) return;
  const access = initialState?.currentUser?.access;
  if (!access) return;
  return data.reduce((acc: any, cur: any) => {
    // 如果router上没有设置access则默认为该菜单不需要权限
    if (access.includes(cur.access) || !cur.access) {
      // 如果菜单可以被搜索则添加
      if (cur.isSearch) {
        cur.label = (
          <div style={{ width: '100%' }} onClick={() => handleRoute(cur.path)}>
            {cur.name}
          </div>
        );
        cur.value = cur.name;

        acc.push(cur);
      }

      if (cur.routes && cur.routes.length > 0) {
        flatTree(cur.routes, treeMap, initialState);
      }
    }

    return acc;
  }, treeMap);
};

const handleRoute = (path: string) => {
  if (!path) return;
  history.push(path);
};

const GlobalHeaderRight: React.FC = () => {
  const { initialState } = useModel('@@initialState');

  const options = flatTree(routes, [], initialState);

  const onSearch = (value: string | undefined) => {
    const route = options.find((v: any) => v.name === value);
    if (route && route.path) {
      history.push(route.path);
    }
  };

  if (!initialState || !initialState.settings) {
    return null;
  }

  const { navTheme, layout } = initialState.settings;
  let className = styles.right;

  if ((navTheme === 'dark' && layout === 'top') || layout === 'mix') {
    className = `${styles.right}  ${styles.dark}`;
  }

  return (
    <Space className={className}>
      <HeaderSearch
        className={`${styles.action} ${styles.search}`}
        placeholder="站内搜索"
        options={options}
        onSearch={(value) => {
          onSearch(value);
        }}
      />
      <span
        className={styles.action}
        onClick={() => {
          window.open('https://pro.ant.design/docs/getting-started');
        }}
      >
        <QuestionCircleOutlined />
      </span>
      <Avatar />
    </Space>
  );
};

export default GlobalHeaderRight;
